import cv2
from PanelDetection import img2hls,tansformBinary,dilated_eroded_img,getLRfits,drawPanel,cal_radius
import numpy as np

# 检测车道
def pipPanel(img):
    color_binary = img2hls(img)
    img_shape = color_binary.shape
    offset_x = 160
    offset_y = 0
    pts1 = np.float32([
        [img_shape[1] * 0.4, img_shape[0] * 0.7],
        [img_shape[1] * 0.6, img_shape[0] * 0.7],
        [img_shape[1] * 1 / 8, img_shape[0]],
        [img_shape[1] * 7 / 8, img_shape[0]]])

    pts2 = np.float32([
        [offset_x, offset_y],
        [img_shape[1] - offset_x, offset_y],
        [offset_x, img_shape[0] - offset_y],
        [img_shape[1] - offset_x, img_shape[0] - offset_y]])

    # 将中部区域进行屏蔽
    cv2.rectangle(color_binary,
                  [int(img_shape[1] * 0.4 + 20), int(img_shape[0] * 0.7)],
                  [int(img_shape[1] * 0.6 - 20), int(img_shape[0])],
                  color=(0, 0, 0),
                  thickness=cv2.FILLED)
    correct_img = tansformBinary(color_binary,pts1,pts2)

    eroded_img = dilated_eroded_img(correct_img)

    left_fit,right_fit = getLRfits(eroded_img)
    out_img = drawPanel(eroded_img,left_fit,right_fit)
    out_img = tansformBinary(out_img, pts2, pts1)
    out_img = cv2.bitwise_or(img,out_img)

    cal_radius(out_img,left_fit,right_fit)
    cv2.imshow("out_img",out_img)

if __name__ == '__main__':
    video = cv2.VideoCapture("./img/up.mp4")
    fps = video.get(cv2.CAP_PROP_FPS)
    success,frame = video.read()
    while success:
        pipPanel(frame)
        success, frame = video.read()

        # 按键退出
        if cv2.waitKey(1) == ord(" "):
            break
        # 1000ms = 1s
        # 1000 / fps 计算每一帧需要的时间
        cv2.waitKey(int(1000 / int(fps)))

    # 释放资源
    video.release()
    # 关闭所有窗口
    cv2.destroyAllWindows()
